<?php

namespace app\push\controller;

use think\Cache;
use think\worker\Server;

class Worker extends Server
{
    protected $socket = 'tcp://www.thinkphp.cc:2346';

    /**
     * 收到信息
     * @param $connection
     * @param $data
     */
    public function onMessage($connection, $data)
    {
        // 发送指令
        $decodeData = json_decode($data, true);
        if(!is_null($decodeData) && array_key_exists('send', $decodeData) && $connections = Cache::store('redis')->get('connections')){
            if(isset($connection->worker->uidConnections[$connections[$decodeData['code']]])){
                $conn = $connection->worker->uidConnections[$connections[$decodeData['code']]];
                $conn->send($decodeData['content']);
                $connection->send('12 12 ok');
                // foreach($connection->worker->connections as $conn){
                //     if($conn->id == $decodeData['uid']){
                //         $conn->send($decodeData['content']);
                //     }
                // }
            }
            $connection->send('fail offline');
        }else{
            // 设备上传
            // 解析
            $s = unpack('Vhead/vcommandStatus/vdataLength/vdataCommand/hcode1/hcode2/hcode3/hcode4/hcode5/hcode6/hcode7/hcode8/hcode9/hcode10/hcode11/hcode12/hcode13/hcode14/hcode15', $data);
            //设备编码
            $deviceCode = '';
            for($i = 1; $i <= 15; $i++){
                $deviceCode .= $s["code$i"];
            }
            
            // 记录链接
            $connections = Cache::store('redis')->get('connections')?: [];
            Cache::store('redis')->set('connections', array_merge($connections, [$deviceCode => $connection->id]));
            $connection->worker->uidConnections = isset($connection->worker->uidConnections)? $connection->worker->uidConnections: array();
            $connection->worker->uidConnections[$connection->id] = $connection;
            

            // 发送消息
            $toConnectionIds = Cache::store('redis')->get('toConnectionIds')?: [];
            if(count($toConnectionIds) && isset($toConnectionIds[$deviceCode])){
                // 设备有用户链接
                foreach($toConnectionIds[$deviceCode] as $connId){
                    \Channel\Client::publish($connection->worker->id, array(
                        'to_connection_id' => $connId,
                       'content' => isset($content)? $content: bin2hex($data),
                    ));
                }
                $connection->send('00 12 ');
            }
            // 设备无用户链接
            $connection->send('00 00 ');
        }
    }

    /**
     * 当连接建立时触发的回调函数
     * @param $connection
     */
    public function onConnect($connection)
    {
        unset($connection->worker->uidConnections[$connection->id]);
    }

    /**
     * 当连接断开时触发的回调函数
     * @param $connection
     */
    public function onClose($connection)
    {

    }

    /**
     * 当客户端的连接上发生错误时触发
     * @param $connection
     * @param $code
     * @param $msg
     */
    public function onError($connection, $code, $msg)
    {
        echo "error $code $msg\n";
    }

    /**
     * 每个进程启动
     * @param $worker
     */
    public function onWorkerStart($worker)
    {
        \Channel\Client::connect('127.0.0.1', 2206);
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        return 'index';
    }

    protected function init()
    {

    }

    
}
